package com.yhp.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;


//登录过滤器,未登录情况下不能访问其他页面
public class loginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Object name = request.getSession().getAttribute("name");
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        if (ignore(request) || name != null) {
            filterChain.doFilter(request, response);//调用下一个过滤器或者servlet
        } else {
            writer.println("<script>location.href='login.jsp'</script>");
        }
    }

    /**
     * 判断请求地址是否是除了登录页面之外的地址，是则返回false,是登录页面则返回true
     *
     * @param req
     * @return
     */
    private boolean ignore(HttpServletRequest req) {
        String[] uris = {"login", "login.jsp", "login.css", ".css", ".css", ".gif", ".jpg", ".png", "js",".jsp"};
        for (String s : uris) {
            if (req.getRequestURI().endsWith(s)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {

    }
}